<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col>
      <!--岗位数据-->
      <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="80px" v-show="showSearch" >
        <el-form-item label="租户名称" prop="tenantName">
          <el-input v-model="queryParams.tenantName" placeholder="请输入租户名称" size="small" clearable style="width: 150px"/>
        </el-form-item>

        <el-form-item label="租户编码" prop="tenantNumber">
          <el-input v-model="queryParams.tenantNumber" placeholder="请输入租户编码" size="small" clearable style="width: 150px"/>
        </el-form-item>

        <el-form-item label="租户简称" prop="tenantAbbreviation">
          <el-input v-model="queryParams.tenantAbbreviation" placeholder="请输入租户简称" size="small" clearable style="width: 150px"/>
        </el-form-item>

        <el-form-item label="管理账号" prop="loginName">
          <el-input v-model="queryParams.loginName" placeholder="请输入管理账号" size="small" clearable style="width: 150px"/>
        </el-form-item>

        <el-form-item label="手机号码" prop="mobileNumber">
          <el-input v-model="queryParams.mobileNumber" placeholder="请输入手机号码" size="small" clearable style="width: 150px"/>
        </el-form-item>

        <el-form-item label="租户状态" prop="statusCode">
          <el-select @change="handleQuery" v-model="queryParams.statusCode" size="small" clearable style="width: 150px" placeholder="请选择">
            <el-option key="" label="全部" value=""/>
            <el-option v-for="item in statusOptions" :key="item.dictCode" :label="item.dictName" :value="item.dictCode"/>
          </el-select>
        </el-form-item>

        <el-form-item label="创建时间">
          <el-date-picker @change="handleQuery" v-model="dateRange" size="small" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"/>
        </el-form-item>

        <el-form-item>
          <el-button type="primary"  size="mini" icon="el-icon-search" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery('queryForm')">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary"  v-hasPermi="['saveSystemTenant']"  icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" v-hasPermi="['updateSystemTenant']"  icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate">修改</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="querySystemTenantPageResList" :columns="columns"></right-toolbar>
      </el-row>

        <el-table ref="multipleTable" :stripe="true" v-loading="loading" :data="dataList" @selection-change="handleSelectionChange"
                  @sort-change='tableSortChange' :default-sort="{prop: 'sort', order: 'descending'}">
          <el-table-column type="selection" align="center"/>
          <el-table-column label="租户名称" align="left" prop="tenantName"/>
          <el-table-column label="租户简称" align="left" prop="tenantAbbreviation"  width="150"/>
          <el-table-column label="租户编码" align="left" prop="tenantNumber"  width="200"/>
          <el-table-column label="管理账号" align="left" prop="loginName"  width="180"/>
          <el-table-column label="手机号码"  align="left" prop="mobileNumber"  width="150"/>
          <el-table-column label="租户状态" sortable='custom'  align="center" prop="statusName" width="150" >
            <template slot-scope="scope">
              <span :style="'color:'+scope.row.statusColor">{{scope.row.statusName}}</span>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="left" prop="createTime" sortable='custom' width="200" />
          <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" v-hasPermi="['updateSystemTenant']" icon="el-icon-edit"  @click="handleUpdate(scope.row)">修改</el-button>
              <el-button size="mini" v-if="scope.row.statusCode==='NORMAL'" type="text" v-hasPermi="['updateSystemTenantStatus']" icon="el-icon-video-pause"  @click="handleStatusChange(scope.row)">禁用</el-button>
              <el-button size="mini" v-if="scope.row.statusCode==='FORBID'" type="text" v-hasPermi="['updateSystemTenantStatus']" icon="el-icon-video-play"  @click="handleStatusChange(scope.row)">启用</el-button>
              <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)" v-hasPermi="['resetSystemTenantUserPassword']">
                <span class="el-dropdown-link">
                  <i class="el-icon-d-arrow-right el-icon--right"></i>更多
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="resetSystemTenantUserPassword" icon="el-icon-key"
                                    v-hasPermi="['resetSystemTenantUserPassword']">重置密码</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>

            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total>0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.rows"
                    @pagination="querySystemTenantPageResList"/>
      </el-col>
    </el-row>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="addUpdateOpen" width="800px" append-to-body>
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="租户名称" prop="tenantName" :rules="{required: true, message: '租户名称必须填写', trigger: 'blur'}">
          <el-input :hide-required-asterisk="true" autocomplete="off" v-model="form.tenantName" placeholder="请输入租户名称" maxlength="200" />
        </el-form-item>

        <el-form-item label="租户简称" prop="tenantAbbreviation" :rules="{required: true, message: '租户简称必须填写', trigger: 'blur'}">
          <el-input autocomplete="off" v-model="form.tenantAbbreviation" placeholder="请输入租户简称" maxlength="30" />
        </el-form-item>

        <el-form-item v-if="form.tenantId === undefined" label="管理帐号" prop="loginName" :rules="{required: true, message: '管理帐号必须填写', trigger: 'blur'}">
          <el-input autocomplete="off" v-model="form.loginName" placeholder="请输入管理帐号" maxlength="15" />
        </el-form-item>

        <el-form-item  v-if="form.tenantId === undefined" label="管理密码" prop="password" :rules="{required: true, message: '管理密码必须填写', trigger: 'blur'}">
          <el-input v-model="form.password"  placeholder="请输入管理密码" type="password" minlength="1" maxlength="16" show-password/>
        </el-form-item>

        <el-form-item label="手机号码" prop="mobileNumber" :rules="{required: true, message: '手机号码必须填写', trigger: 'blur'}">
          <el-input autocomplete="off" v-model="form.mobileNumber" placeholder="请输入手机号码" minlength="11" maxlength="11" />
        </el-form-item>

        <el-col :span="24">
          <el-form-item label="功能菜单">
            <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event)">展开</el-checkbox>
            <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event)">全选</el-checkbox>
            <el-tree
              class="flow-tree"
              :data="menuOptions"
              check-on-click-node
              show-checkbox
              ref="menu"
              node-key="id"
              empty-text="加载中，请稍候"
              :props="menuDefaultProps"
            ></el-tree>
          </el-form-item>
        </el-col>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancelAddUpdateOpen">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import {querySystemTenantPageResList, saveSystemTenant, updateSystemTenant, updateSystemTenantStatusByTenantId, querySystemMenuIdListByTenantId,resetSystemTenantUserPassword} from '@/api/system/systemTenant'
  import { queryTenantBindingUseMenuTreeResList } from '@/api/system/systemMenu'
  import { getDicListByDictCodeList } from '@/api/common/dict'
  //默认查询参数
  let defaultQueryParams = {
    tenantName: undefined,
    tenantAbbreviation: undefined,
    startTime: undefined,
    endTime: undefined,
    tenantNumber: undefined,
    statusCode: "",
    loginName: undefined,
    mobileNumber: undefined,
    page: 1,
    rows: 10
  }
  export default {
    name: "systemTenantAdmin",
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 显示搜索条件
        showSearch: true,
        // table表格数据
        dataList: [],
        // 日期范围
        dateRange: [],
        // 弹出层标题
        title: "",
        // 是否显示新增修改弹出层
        addUpdateOpen: false,
        // 租户状态
        statusOptions: [],
        // 菜单列表
        menuOptions: [],
        //展开/折叠
        menuExpand: false,
        //全选/全不选
        menuNodeAll: false,
        //defaultProps(默认参数)
        menuDefaultProps: {
          children: "children",
          label: "menuName"
        },
        // 增加修改表单参数
        form: {},
        // 查询参数
        queryParams: { ...defaultQueryParams },
        //列信息
        columns: [],
      }
    },
    created() {
      this.querySystemTenantPageResList();
      this.initDict();
    },
    methods: {
      //获取数据字典
      initDict(){
        let dictArr = ["STATUS"];
        getDicListByDictCodeList(dictArr).then(res => {
          this.statusOptions = JSON.parse(JSON.stringify(res.data['STATUS']));
        });
      },
      /** 查询租户列表 */
      querySystemTenantPageResList() {
        this.loading = true
        querySystemTenantPageResList(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.dataList = response.data.records
          this.total = response.data.total
          this.loading = false
        })
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.tenantId)
        this.single = selection.length !== 1;
        this.multiple = !selection.length
      },
      //排序
      tableSortChange(column){
        //格式化排序参数，构建中
        this.orderByFormat(this.queryParams,column);
        //执行查询方法
        this.querySystemTenantPageResList()
      },
      // 更多操作触发
      handleCommand(command, row) {
        switch (command) {
          case "resetSystemTenantUserPassword":
            this.resetSystemTenantUserPassword(row);
            break;
          default:
            break;
        }
      },

      /** 重置密码按钮操作 */
      resetSystemTenantUserPassword(row) {
        this.$prompt('请输入"' + row.tenantName + '"的新密码', "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          closeOnClickModal: false,
          inputPattern: /^.{1,16}$/,
          inputErrorMessage: "用户密码长度必须介于 1 和 16 之间"
        }).then(({ value }) => {
          resetSystemTenantUserPassword({"tenantId":row.tenantId,"password": value}).then(response => {
            this.$modal.msgSuccess("密码重置成功，新密码是：" + value);
          });
        }).catch(() => {});
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.queryBindingTenantUseMenuTreeResList(undefined);
        this.addUpdateOpen = true;
        this.title = "添加租户";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        row = row.isTrusted ? this.$refs.multipleTable.selection[0] : row;
        //修改表单填充
        this.form = {...row};
        this.queryBindingTenantUseMenuTreeResList(row.tenantId);
        this.addUpdateOpen = true;
        this.title = "修改租户";
      },

      // 租户户状态修改
      handleStatusChange(row) {
        let text = row.statusCode === "NORMAL" ? "禁用" : "启用";
        this.$modal.confirm('确认要"' + text + '""' + row.tenantName + '"租户吗？').then(function() {
          return updateSystemTenantStatusByTenantId({"tenantId":row.tenantId});
        }).then(() => {
          this.querySystemTenantPageResList()
          this.$modal.msgSuccess("【"+row.tenantName+"】租户"+text + "成功");
        }).catch(function() {

        });
      },

      /** 提交保存或修改按钮 */
      submitForm: function() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.form.menuIdList=this.getMenuAllCheckedKeys()
            if (this.form.tenantId !== undefined) {
              updateSystemTenant(this.form).then(response => {
                this.$modal.msgSuccess(response.message)
                this.querySystemTenantPageResList();
                this.addUpdateOpen = false
              });
            } else {
              saveSystemTenant(this.form).then(response => {
                this.$modal.msgSuccess(response.message)
                this.querySystemTenantPageResList();
                this.addUpdateOpen = false
              });
            }
          }
        });
      },
      /** 查询菜单树结构 */
      queryBindingTenantUseMenuTreeResList(tenantId) {
        queryTenantBindingUseMenuTreeResList().then(response => {
          this.menuOptions = response.data;
          if (tenantId!==undefined){
            this.$nextTick(() => {
              this.setMenuCheckedKeys(tenantId);
            });
          }
        });
      },


      //设置菜单tree默认选中
      setMenuCheckedKeys(tenantId){
        querySystemMenuIdListByTenantId({"tenantId":tenantId}).then(response => {
          let menuIdArr=[];
          const dataRes = response.data;
          for (let j = 0; j < dataRes.length; j++) {
            const menuId = dataRes[j];
            let key=this.getNodeKeys(menuId,this.menuOptions);
            if(key!==''){
              menuIdArr.push(key);
            }
          }
          //设置选中节点
          this.$refs.menu.setCheckedKeys(menuIdArr);
          //设置全选中
          this.menuNodeAll = this.menuOptions.length===dataRes.length;
        });
      },
      // 所有菜单节点数据
      getMenuAllCheckedKeys() {
        // 目前被选中的菜单节点
        let checkedKeys = this.$refs.menu.getCheckedKeys();
        // 半选中的菜单节点
        let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
        checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
        return checkedKeys;
      },
      //获取选中的子节点
      getNodeKeys(keyId,childrens){
        let key="";
        for (let i = 0; i < childrens.length; i++) {
          const item = childrens[i];
          let id=item.id;
          let childs=item.children;
          if(id===keyId){//如果相等
            if(childs&&childs.length>0){
              key=this.getNodeKeys(keyId,childs)
            }else{  //没有子节点
              return keyId;
            }
          }else if(childs&&childs.length>0){
            key=this.getNodeKeys(keyId,childs);
          }
          if(key!==''){
            return key;
          }
        }
        return key;
      },
      // 树权限（展开/折叠）
      handleCheckedTreeExpand(value) {
        let treeList = this.menuOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
        }
      },
      // 树权限（全选/全不选）
      handleCheckedTreeNodeAll(value) {
        this.$refs.menu.setCheckedNodes(value ? this.menuOptions: []);
      },


      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.page = 1
        this.querySystemTenantPageResList()
      },
      /** 重置按钮操作 */
      resetQuery(fromId) {
        this.dateRange = [];
        this.resetForm(fromId);
        this.handleQuery()
      },
      // 取消修改增加弹出层按钮
      cancelAddUpdateOpen() {
        this.addUpdateOpen = false
      },
      // 表单重置
      reset() {
        this.menuOptions = []
        if (this.$refs.menu !== undefined) {
          this.$refs.menu.setCheckedKeys([]);
        }
        this.form = {
          tenantId: undefined,
          tenantName: undefined,
          tenantAbbreviation: undefined,
          loginName: undefined,
          password: undefined,
          mobileNumber: undefined,
          menuIdList: [],
          statusOptions: []
        };
        this.resetForm('form')
      }
    }
  }
</script>
<style rel="stylesheet/scss" lang="scss">
  .flow-tree{
    overflow-y:auto;
    border:1px solid #E7E7E7;
    height:300px;
  }
</style>
